package data

import (
	"github.com/go-kratos/kratos/v2/errors"
	"go_private_im/internal/logic/biz"
	"gorm.io/gorm"
	"strconv"
	"context"
)


func (l *LogicRepo) GetUserAcceptsRooms (req *biz.ConnectReq) (accepts []int32) {
	room := []*biz.RoomDetailInfo{}
	if err := l.data.Db.Table("room_detail").Where("user_id = ?",req.Token.UserId).Select("room_id").Find(&room).Error; err != nil{
		return
	}
	for _,v := range room {
		id,_ := strconv.Atoi(v.RoomId)
		accepts = append(accepts,int32(id))
	}
	return
}



func (l *LogicRepo) GetUser(ctx context.Context,userId int64) (user *biz.User, err error)  {
	user = &biz.User{}
	if err = l.data.Db.Table("user").Where("id = ? and type = 0",userId).Take(&user).Error; err != nil{
		if errors.Is(err,gorm.ErrRecordNotFound) {
			err = errors.NotFound("用户不存在","用户不存在")
		}
		return
	}
	return
}

func (l *LogicRepo) GetUsers(ctx context.Context,userId []string) (users []*biz.User, err error)  {
	users = []*biz.User{}
	if err = l.data.Db.Table("user").Where("id in ?",userId).Find(&users).Error; err != nil{
		if errors.Is(err,gorm.ErrRecordNotFound) {
			err = errors.NotFound("查询用户不存在","查询用户不存在")
		}
		return
	}
	return
}

func (l *LogicRepo) UpdataUser(ctx context.Context,user *biz.User) (err error)  {
	if err = l.data.Db.Table("user").Updates(user).Error; err != nil{
		return
	}
	return
}

func (l *LogicRepo) DelUser(ctx context.Context,user *biz.User) (err error)  {
	if err = l.data.Db.Table("user").Delete(user).Error; err != nil{
		return
	}
	return
}

func (l *LogicRepo) Login(ctx context.Context,user *biz.LoginArg) (authToken *biz.AuthToken,err error) {
	if err = l.data.Db.Table("user").Where("id = ? and type = 0",user.UserId).Take(&authToken).Error; err != nil{
		if errors.Is(err,gorm.ErrRecordNotFound) {
			err = errors.NotFound("用户不存在","用户不存在")
		}
		return
	}
	l.data.Db.Table("user").Where("id = ? and type = 0",user.UserId).Update("status",1)
	return
}

func (l *LogicRepo) LoginOut(ctx context.Context,user *biz.LoginArg)  error {
	if err := l.data.Db.Table("user").Where("id = ? and type = 0",user.UserId).Update("status",0).Error; err != nil{
		return err
	}
	return nil
}

//判断用户是否在某个群
func (l *LogicRepo) IsUserInRoom(userId int64,roomId int64) bool {
	userRoom := map[string]interface{}{}
	if err := l.data.Db.Table("room_detail").Where("user_id = ? and room_id = ?",userId,roomId).Select("id").Take(&userRoom).Error; err != nil {
		if !errors.Is(err,gorm.ErrRecordNotFound) {
			l.log.Error("IsUserInRoom 查询 error",err)
		}
		return false
	}
	return true
}
